<template>
  <div class="app-container">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="edit-form" :style="{'height': formHeight}">
        <el-row>
          <el-col :span="22" v-if="restEnable">
            <el-form-item label="餐饮商户" prop="restaurantId">
              <el-select
                ref="restaurantId"
                v-model="form.restaurantId"
                filterable
                remote
                reserve-keyword
                default-first-option
                style="width: 100%"
                placeholder="请选择商店"
                :remote-method="getRestaurantList"
                :loading="restLoading">
                <el-option
                  v-for="item in restOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="名称" prop="name">
              <el-input ref="name" v-model="form.name" placeholder="请输入菜品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="种类" prop="typeId">
              <el-select ref="typeId" v-model="form.typeId" placeholder="请选择菜品种类">
                <el-option
                  v-for="dict in menuTypeList"
                  :key="dict.id"
                  :label="dict.typeName"
                  :value="dict.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="价格（元）" prop="price">
              <el-input-number ref="price" v-model="form.price" placeholder="请输入菜品价格" controls-position="right" :step="1" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="会员价（元）" prop="vipPrice">
              <el-input-number v-model="form.vipPrice" placeholder="请输入菜品会员价" controls-position="right" :step="1" :precision="2"/>
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="推荐指数" prop="recValue" v-hasPermi="['shop:goods:rec']">
              <el-input v-model="form.recValue" placeholder="请输入推荐指数" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.shop_goods_status"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="缩略图" prop="imgAbbrev">
              <image-upload ref="imgAbbrev" v-model="form.imgAbbrev" :biz-id="menuId" biz-code="SHOP_REST_M_ABBREV" :limit="1" @input="imgAbbrevChange"/>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="轮播图" prop="imgDetails">
              <image-upload ref="imgDetails" v-model="form.imgDetails" :biz-id="menuId" biz-code="SHOP_REST_M_DETAIL" zoom="0"/>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="亮点" prop="feature">
              <el-tooltip content="可自定义输入亮点" placement="top">
                <el-select
                  v-model="feature"
                  multiple
                  filterable
                  allow-create
                  default-first-option
                  style="width: 100%"
                  placeholder="请选择或输入亮点">
                  <el-option
                    v-for="item in featureOptions"
                    :key="item.value"
                    :label="item.value"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-tooltip>
<!--              <el-input v-model="form.feature" type="textarea" placeholder="请输入亮点-建议使用 @@ 符号分隔多项" title="建议使用 @@ 符号分隔多项"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item label="菜品详情">
              <editor v-model="form.content" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
  </div>
</template>

<script>
import { getRestMenu, addRestMenu, updateRestMenu } from "@/api/shop/restMenu";
import { getRestaurant, listRestaurant } from "@/api/shop/restaurant";
import { listMenuType } from "@/api/shop/menuType";

export default {
  name: "RestMenuAdd",
  dicts: ['shop_dish_type', 'shop_goods_status'],
  data() {
    return {
      // 表单的高度
      formHeight: document.documentElement.scrollHeight - 160 + "px",
      // 菜品
      menuId: null,
      // 餐饮商户
      restId: null,
      // 餐饮菜品表格数据
      restMenuList: [],
      // 餐饮菜品类型数据
      menuTypeList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        restaurantId: [
          { required: true, trigger: "blur", message: "请选择餐饮商户" }
        ],
        name: [
          { required: true, trigger: "blur", message: "请输入菜品名称" }
        ],
        price: [
          { required: true, trigger: "blur", message: "请输入菜品价格" }
        ],
        imgAbbrev: [
          { required: true, trigger: "blur", message: "请上传缩略图" }
        ],
        imgDetails: [
          { required: true, trigger: "blur", message: "请上传轮播图" }
        ],
      },
      // 餐饮商户数据源
      restOptions: [],
      // 餐饮商户遮罩层
      restLoading: true,
      // 亮点
      featureOptions: [{
        value: '快餐美食'
      }, {
        value: '甜品'
      }],
      // 亮点接收设置
      feature: [],
    };
  },
  created() {
    this.reset();
    const menuId = this.$route.query && this.$route.query.menuId;
    const restId = this.$route.query && this.$route.query.restId;
    if (menuId) {
      this.menuId = Number(menuId)
      this.getInfo(menuId);
    } else {
      this.getRestaurantList();
    }
    if (restId) {
      this.restId = restId;
    }
    if (!menuId && restId) {
      this.getRest(restId);
      this.getTypeList(this.restId);
    }
  },
  computed: {
    // 是否禁用
    restEnable() {
      return !this.restId;
    },
  },
  methods: {
    /** 查询餐饮菜品列表 */
    getInfo(id) {
      getRestMenu(id).then(response => {
        this.form = response.data;
        this.form.price /= 100;
        this.form.vipPrice /= 100;
        this.feature = this.stringToList(this.form.feature);
        this.getRest(response.data.restaurantId);
        this.getTypeList(this.form.restaurantId);
      });
    },
    /** 查询餐饮商户详情 */
    getRest(id) {
      getRestaurant(id).then(response => {
        this.restOptions.push(response.data);
        this.form.restaurantId = id;
      });
    },
    /** 查询餐饮商户列表 */
    getRestaurantList(query) {
      if (query !== '') {
        this.restLoading = true;
        const queryParams = {
          name: query
        }
        listRestaurant(queryParams).then(response => {
          this.restOptions = response.rows;
          this.restLoading = false;
        });
      }
    },
    /** 查询餐饮商户详情 */
    getTypeList(restId) {
      listMenuType({restaurantId: restId}).then(response => {
        this.menuTypeList = response.rows;
      });
    },
    // 取消按钮
    cancel() {
      const obj = { path: "/shop/restaurant/menu", query: {restId: this.restId}};
      this.$tab.closeOpenPage(obj);
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        restaurantId: null,
        imgAbbrev: null,
        name: null,
        imgDetails: null,
        type: null,
        vipPrice: null,
        price: null,
        recValue: null,
        feature: null,
        content: null,
        status: "1",
        isDel: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid, object) => {
        if (valid) {
          this.buildOther();
          if (this.form.id != null) {
            updateRestMenu(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
            });
          } else {
            addRestMenu(this.form).then(response => {
              // this.form.price /= 100;
              // this.form.vipPrice /= 100;
              this.$modal.msgSuccess("新增成功");
              this.menuId = response.data.id;
              this.form.id = response.data.id;
            });
          }
        } else {
          let str = []
          for (let key in object) {
            object[key].map(item => {
              str.push(item.message)
            })
            let dom = this.$refs[Object.keys(object)[0]]
            if (Object.prototype.toString.call(dom) !== '[object Object]') {
              dom = dom[0]
              break
            }
            // 定位代码
            dom.$el.scrollIntoView({
              block: 'center',
              behavior: 'smooth'
            });
          }
          this.$modal.msgError(str.join(', '));
        }
      });
    },
    async buildOther() {
      this.form.feature = this.listToString(this.feature);
    },
    /** 提取url到form，用于保存 */
    imgAbbrevChange(val) {
      if (val && val.length) {
        this.form.imgAbbrev = val[0].url;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || "@@";
      for (let i in list) {
        strs += list[i] + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 2) : '';
    },
    // 对象转成指定字符串分隔
    stringToList(string, separator) {
      separator = separator || "@@";
      var list = string.split(separator);
      return list;
    }
  }
};
</script>
<style>
.edit-form {
  overflow-y: auto;
}
</style>
